package com.atguigu.service_order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.service_order.entity.TOrder;
import com.atguigu.service_order.entity.TPayLog;
import com.atguigu.service_order.mapper.TPayLogMapper;
import com.atguigu.service_order.service.TOrderService;
import com.atguigu.service_order.service.TPayLogService;
import com.atguigu.service_order.utils.ConstantPropertiesUtil;
import com.atguigu.service_order.utils.HttpClient;
import com.atguigu.servicebase.exception.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author clark
 * @since 2020-11-19
 */
@Service
public class TPayLogServiceImpl extends ServiceImpl<TPayLogMapper, TPayLog> implements TPayLogService {

    @Autowired
    private TOrderService tOrderService;

    @Override
    public Map createNative(String orderNo) {
        try{
            //1 根据订单号查询订单信息
            QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("order_no",orderNo);
            TOrder order = tOrderService.getOne(wrapper);
            //2 使用map设置生成二维码需要参数
            Map<String, String> m = new HashMap<>();
            m.put("appid", ConstantPropertiesUtil.APP_ID);
            m.put("mch_id",ConstantPropertiesUtil.PARTNER);
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("body",order.getCourseTitle());
            m.put("out_trade_no",orderNo);
            m.put("total_fee",order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            m.put("spbill_create_ip","127.0.0.1");
            m.put("notify_url",ConstantPropertiesUtil.NOTIFY_URL);
            m.put("trade_type","NATIVE");
            //3 使用httpclient请求 传递参数xml格式 微信支付提供的固定的地址
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(m,ConstantPropertiesUtil.PARTNER_KEY));
            httpClient.setHttps(true);
            //执行发送
            httpClient.post();
            //4 得到发送请求返回结果
            //返回内容，是使用xml格式返回，因为传递的参数是xml格式
            String xml = httpClient.getContent();
            //将XML转成map
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);
            //最终返回数据的封装
            Map<String, Object> map = new HashMap<>();
            map.put("out_trade_no",orderNo);
            map.put("course_id",order.getCourseId());
            map.put("total_fee",order.getTotalFee());
            map.put("result_code",resultMap.get("result_code"));
            map.put("code_url",resultMap.get("code_url"));

            return map;
        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"生成二维码失败");
        }
    }
    //查询订单的支付状态
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try{
            Map<String, String> m = new HashMap<>();
            m.put("appid", ConstantPropertiesUtil.APP_ID);
            m.put("mch_id",ConstantPropertiesUtil.PARTNER);
            m.put("nonce_str", WXPayUtil.generateNonceStr());
            m.put("out_trade_no",orderNo);

            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(m,ConstantPropertiesUtil.PARTNER_KEY));
            httpClient.setHttps(true);
            httpClient.post();

            String xml = httpClient.getContent();
            Map<String,String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;

        }catch (Exception e){
            e.printStackTrace();
            throw new GuliException(20001,"查询失败");
        }
    }


    //添加支付记录和更新订单状态
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        String orderNo = map.get("out_trade_no");
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_no",orderNo);
        TOrder order = tOrderService.getOne(wrapper);

        //更新订单状态
        if(order.getStatus().intValue() == 1){
            return;
        }
        order.setStatus(1);
        tOrderService.updateById(order);

        //添加支付记录
        TPayLog tPayLog = new TPayLog();
        tPayLog.setOrderNo(orderNo);//订单号
        tPayLog.setPayTime(new Date());//订单完成时间
        tPayLog.setPayType(1);//支付类型 1 微信
        tPayLog.setTotalFee(order.getTotalFee());
        tPayLog.setTradeState(map.get("trade_state"));
        tPayLog.setTransactionId(map.get("transaction_id"));
        tPayLog.setAttr(JSONObject.toJSONString(map));
        baseMapper.insert(tPayLog);


    }
}
